<?php
/**
 * Created by PhpStorm.
 * User: Larry
 * Date: 16/3/29
 * Time: 23:04
 */

namespace App\Services\Wechat;

use DB;
use App\Models\BuyCode;
use Request;

class Buy
{
    /**
     * @var Buy
     */
    private $buy, $buycode;

    /**
     * Buy constructor.
     * @param Buy $buy
     * @param BuyCode $buyCode
     */
    public function __construct(\App\Models\Buy $buy, BuyCode $buyCode)
    {
        $this->buy = $buy;
        $this->buycode = $buyCode;
    }

    public function add($carts, $uid, $yuncode, $sn)
    {
        DB::beginTransaction();
        try{
            $dataY['uid'] = $uid;
            $dataY['money'] = $carts['money'];
            $dataY['goods_id'] = $carts['goods_id'];
            $dataY['periods_id'] = $carts['qishu'];
            $dataY['addtime'] = $this->microtime_float();
            $dataY['ip'] = Request::getClientIp();
            $dataY['sn'] = $sn;
            $res = $this->buy->add($dataY);

            $dataZ['uid'] = $uid;
            $dataZ['buy_id'] = $res;
            $dataZ['goods_id'] = $carts['goods_id'];
            $dataZ['periods_id'] = $carts['qishu'];
            $dataZ['code'] = $yuncode;
            $this->buycode->add($dataZ);
            DB::commit();
            return true;
        }catch(\Exception $e){
            DB::rollBack();
            return false;
        }
    }

    function microtime_float()
    {
        return date("Y-m-d H:i:s").'.'.substr(explode( ".", microtime ())[1], 0, 3);//输出格式 2016-03-2922:55:42.822
    }

}